package com.tengju.support.domain.model.rule;

import com.google.common.collect.Lists;
import com.tengju.support.domain.shared.DomainException;
import com.tengju.support.domain.shared.DomainExceptionCode;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;

public class RuleFactory {

    public static Rule createFullMatchRule(FullMatchRuleForm form,String operator) {

        if (form == null || CollectionUtils.isEmpty(form.getNodes())) {
            throw DomainException.error(DomainExceptionCode.RULE_EMPTY);
        }

        List<FullMatchRuleNodeForm> nodes = form.getNodes();

        if (form.getBizType() == null) {
            throw DomainException.error(DomainExceptionCode.RULE_BIZ_TYPE_EMPTY);
        }

        List<RuleNode> ruleNodes = Lists.newArrayList();

        //form 只在再facade
        for (FullMatchRuleNodeForm node: nodes) {
            //创建全匹配condition
            Condition fullMatchCondition =
                    Condition.createFullMatchCondition(node.getConditionForms());
            //创建action对象
            List<Action> actions = Lists.newArrayList();

            if (!CollectionUtils.isEmpty(node.getActionForms())) {

                for (int i = 0; i < node.getActionForms().size(); i++) {
                    ActionForm actionForm = node.getActionForms().get(i);
                    try {
                        Class<?> actionClass = Class.forName(actionForm.getActionType().getClassPath());
                        Constructor<?> constructor = actionClass.getConstructor(Map.class);
                        Action action = (Action) constructor.newInstance(actionForm.getActionInfo());
                        actions.add(action);
                    } catch (Exception e) {
                        throw DomainException.error(DomainExceptionCode.RULE_ACTION_PARSE_ERROR);
                    }
                }

            }

            RuleNode ruleNode = new RuleNode(fullMatchCondition, actions);
            ruleNodes.add(ruleNode);

        }

        return new Rule(null,
                form.getRuleDesc(),
                ruleNodes,
                form.getBizType(),
                operator,
                operator);

    }



}
